const {createCanvas,loadImage} = require('canvas')
const ratio = 0.1

function watermark(pic,wm){
    loadImage(pic).then((myimg)=>{
        loadImage(wm).then(wming=>{
            const canvas = createCanvas(myimg.width,myimg.height)
            const ctx = canvas.getContext('2d')
            ctx.drawImage(myimg,0,0)
            //随机打水印
            //计算旋转贴图的最大尺寸
            const long = Math.sqrt(wming.width*wming.width + wming.height*wming.height)
            const halflong = long/2
            //背景图的最长边
            const bglong = Math.max(myimg.width,myimg.height)
            //贴图的缩放比
            const signscale = bglong / long * ratio
            //贴图画布边长按比例缩放
            const vmlong = long * signscale
            //创建贴图的画布
            const canvas1 = createCanvas(vmlong,vmlong)
            //获取贴图的绘画区
            const ctx1 =canvas1.getContext('2d')
            //贴图的绘图区缩放
            ctx1.scale(signscale,signscale)
            //贴图的绘图区移到中心点
            ctx1.translate(halflong,halflong)
            //贴图的绘图区围尧中心点
            ctx1.rotate((Math.random() - 0.5)* Math.PI/2)
            //贴图的绘图区返回原点
            ctx1.translate(-halflong,-halflong)
            //在贴图的绘图区中心点绘制贴图
            ctx1.drawImage(wming,(long-wming.width)/2,(long-wming.height)/2)
            //随机生成贴图绘制在底图上的位置
            const posx = (myimg.width - vmlong) * Math.random()
            const posy = (myimg.height - vmlong)* Math.random()

            console.log(posx,posy)

            ctx.drawImage(canvas1,posx,posy)



            const fs=require('fs')
            const out = fs.createWriteStream(__dirname+'/'+pic)
            const stream = canvas.createPNGStream()
            stream.pipe(out)
            out.on('finish',()=>console.log('the png file is created. '))
        })
    })
}



module.exports = watermark
watermark('./bg.png','./uploads/watermark.png')

console.log('执行成功')

